package logparser.bean;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class ParserNearbyFootball extends Parser implements IParser{
	private String m_pid;
	private String m_tid;
	private String m_level;
	private String m_file;
	private String m_line;
	private String m_function;
	private String m_msg;
	private String m_date;
	private String m_tz;
	private static final String LOG_TAG = "[NearbyFootball]";
	private File m_outputFile;
	private DataOutputStream m_writer; 
	private boolean m_valid = false;
	private static final Logger logger = LogManager.getLogger(ParserNearbyFootball.class);
	private HashMap<Integer,String> m_processes = new HashMap<Integer,String>();
	private static final String AppKeyWord = "nearbyfootball";
	
	
	
	public String toCSVFormat(ParserLine parse) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder()
				.append(m_date + ",")
				.append(parse.getTag() + ",")
				.append(ParserSystem.csvHandlerStr(m_msg) + ",")
				.append(m_pid + ",")
				.append(m_tid + ",")
				.append(m_file + ":" + m_line + ",")
				.append(m_function + ",")
				.append(m_tz + ",")
				.append(parse.getOrigLine())
				.append(parse.getProcessName() + ",")
				.append(m_level + ",")
				.append("\n")
				;
		if(!m_valid){
			return "";
		}
		return sb.toString();
	}

	public String toCSVHead() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder()
				.append("date,")
				.append("tag,")
				.append("msg,")
				.append("pid,")
				.append("tid,")
				.append("file&line,")
				.append("function,")
				.append("timezone,")
				.append("origline")
				.append("appname,")
				.append("level,")
				.append("\n");
		return sb.toString();
	}
	
	
	@Override
	public void processStart() throws Exception{
		// TODO Auto-generated method stub
		String appFolder = m_output_folder + File.separator + "app_football";
		new File(appFolder).mkdirs();
		m_outputFile = new File(appFolder + "/football.csv");
		m_writer = new DataOutputStream(new FileOutputStream(m_outputFile));
		m_writer.write(utf8Head);
		CaptureSave.writeUTF8String(m_writer, toCSVHead());
		m_processes.clear();
	}

	@Override
	public void processEnd() {
		// TODO Auto-generated method stub
		try {
			m_writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	private boolean containsFootballLog(String line,ParserLine parse){
		if(m_processes.containsKey(Integer.parseInt(parse.getProcessId()))){
			return true;
		}
		
		if(!parse.getProcessName().isEmpty()){
			if(m_processes.containsValue(parse.getProcessName())){
				return true;
			}
		}
		
//		if(parse.getMsg().toLowerCase().contains(AppKeyWord)){
//			return true;
//		}
		
		return false;
		
	}
	
	
	@Override
	public boolean processLine(String line,ParserLine parse) {
		// TODO Auto-generated method stub
		if(!parse.getTag().contains(LOG_TAG)){
			if(containsFootballLog(line,parse)){
				try {
					m_pid = parse.getProcessId();
					m_tid = "";
					m_level = "";
					m_file = "";
					m_line = "";
					m_function = "";
					m_date = "";
					m_tz = "";					
					m_msg = parse.getMsg();
					CaptureSave.writeUTF8String(m_writer,toCSVFormat(parse));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}			
			return false;
		}
		
		logger.debug("process line:" + line);
		
		String msg = parse.getMsg();
		String left;
		
		Matcher matcher;
		String regStr;
		regStr = "(\\d+)-(\\d+)-(\\d+)\\s*(\\d+):(\\d+):(\\d+).(\\d+),";
		matcher = Pattern.compile(regStr).matcher(msg);
		if(matcher.find()){
			m_msg = msg.substring(matcher.end());
			left = msg.substring(0,matcher.end());
		}else{
			m_valid = true;
			m_msg = msg;
			try {
				CaptureSave.writeUTF8String(m_writer, toCSVFormat(parse));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
	
		String[] arrayStr = left.split(",");
		int i = 0;
		m_pid = arrayStr[i++];
		m_tid = arrayStr[i++];
		m_level = arrayStr[i++];
		m_file = arrayStr[i++];
		m_line = arrayStr[i++];
		m_function = arrayStr[i++];
		m_tz = arrayStr[i++];
		m_date = arrayStr[i++];
		
		m_valid = true;		
		try {
			CaptureSave.writeUTF8String(m_writer, toCSVFormat(parse));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		m_processes.put(Integer.parseInt(m_tid),parse.getProcessName());
		
		return true;
	}

}
